/*
 * Copyright (c) 2009 Sun Microsystems, Inc.
 * Copyright (c) 2011 Oracle Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

package com.sun.spot.wot;

import com.sun.spot.core.util.Properties;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Enumeration;
import com.sun.spot.wot.http.HttpRequest;
import com.sun.spot.wot.http.HttpResponse;

/**
 *
 * @author vgupta
 */
public abstract class WebApplication {
    String defaultPropStr = "uri:/\n" +
            "realm: default realm\n" +
            "tags:\n";

    Properties defaultProps = new Properties();
    Properties props = null;

    public abstract void init();

    public WebApplication() {
        try {
            defaultProps.load(new ByteArrayInputStream(defaultPropStr.getBytes()));
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        props = new Properties(defaultProps);
        init();
    }
    
    public WebApplication(String propertiesString) {
        try {
            defaultProps.load(new ByteArrayInputStream(defaultPropStr.getBytes()));
            props = new Properties(defaultProps);
            this.props.load(new ByteArrayInputStream(propertiesString.getBytes()));
            init();
        } catch (IOException ex) {
            System.err.println("WebApplication constructor caught " + ex);
            ex.printStackTrace();
        }
    }

    Properties getProperties() {
        return props;
    }

    String getPropertiesStr(String format) {
        StringBuffer sb = new StringBuffer();
        String pkey = getProperty("uri");
        String pval = null;

        if (format.equalsIgnoreCase("text")) {
            sb.append("<" + pkey + ">");
            Enumeration pkeys = getProperties().keys();
            while (pkeys.hasMoreElements()) {
                pkey = (String) pkeys.nextElement();
                pval = props.getProperty(pkey);
                if (pkey.equalsIgnoreCase("uri") || pval == null) {
                    continue;
                }
                sb.append(";" + pkey + "=" + pval);
            }
            sb.append("\n");
        } else {
            String name = props.getProperty("n");
            String desc = props.getProperty("d");
            String shortURL = props.getProperty("sh");

            sb.append("<tr>");
            sb.append("<td><a href=\".." + pkey + "\">" + pkey +
                    "</a>" +
                    ((shortURL == null) ? "" : 
                        (", <a href=\"../" + shortURL + "\">/" + shortURL + "</a>")) +
                    "</td>");

            if (desc != null) {
                sb.append("<td><a href=\"" + desc + "\">" +
                        ((name != null) ? name : desc) +
                        "</a></td>");
            } else {
                sb.append("<td>" + ((name != null) ? name : "")  + "</td>");
            }

            sb.append("</tr>\n");
        }

        return sb.toString();
    }

    private boolean valuesMatch(String val, String qval) {
        
        if (val.equalsIgnoreCase(qval)) return true;

        return false;
    }

    boolean matchesQuery(String queryStr) {
        if (queryStr == null) return true;
        int idx = queryStr.indexOf('=');
        if (idx < 0) return false;
        String qkey = queryStr.substring(0, idx);
        String qval = queryStr.substring(idx + 1);
        String val = getProperty(qkey);

        if (val != null) {
            return valuesMatch(val, qval);
        } 
        
        return false;
    }
    
    public String getProperty(String key) {
        String result = props.getProperty(key);

        return result;
    }

    public void setProperty(String key, String value) {
        props.setProperty(key, value);
    }

    public boolean isAuthorized(HttpRequest request) {
        return true;
    }

    public abstract HttpResponse processRequest(HttpRequest request)
            throws IOException;


    // Add a bunch of helper methods here? e.g URI encoding/decoding,
    // parameter parsing etc or maybe have them in a separate URI class
}
